<template>
  <div class="left-content-container">
    <div class="content">
      <div class="flex-column">
        <!-- 添加标题栏 -->
        <div class="header-actions">
          <div class="title"></div>
          <div class="action-buttons">
            <el-tooltip class="item" effect="dark" content="刷新" placement="bottom">
              <el-icon class="action-icon" @click="refreshAllFences"><Refresh /></el-icon>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="强制重载页面" placement="bottom">
              <el-icon class="action-icon reload-icon" @click="forceReload"><RefreshRight /></el-icon>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="新增类型" placement="bottom">
              <el-icon class="action-icon" @click="showAddEnvType"><Plus /></el-icon>
            </el-tooltip>
          </div>
        </div>
        <div v-infinite-scroll="load" class="shipContent custom-scrollbar">
          <el-collapse v-model="activeNames">
            <el-collapse-item v-for="item in datalist" :key="item.id" :name="item.id" >
              <template #title>
                <div class="collapse-header" @click="changeCollapse(item)">
                  <div class="collapse-title" >
                    <!-- <el-icon class="collapse-icon" :class="{ active: item.isActive }"><ArrowRight /></el-icon> -->
                    <div class="envName">{{ item.name }}</div>
                  </div>

                  <div class="collapse-actions">
                    <el-tooltip class="item" effect="dark" content="规则" placement="bottom">
                      <el-icon class="action-icon" @click.stop="setrule(item)"><Setting /></el-icon>
                    </el-tooltip>

                    <el-tooltip class="item" effect="dark" content="添加" placement="bottom">
                      <el-icon class="action-icon" @click.stop="handToAdd(item)"><Plus /></el-icon>
                    </el-tooltip>
                    
                    <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
                      <el-icon class="action-icon" @click.stop="deleteMainItem(item)"><Delete /></el-icon>
                    </el-tooltip>
                  </div>
                </div>
              </template>
              <div v-for="ite in item.list" :key="ite.id" class="envItem" @click="clickToCenterMap(ite)">
                <div class="envItem-name">{{ ite.name }}</div>
                <div class="envItem-actions">
                  <el-tooltip class="item" effect="dark" content="修改" placement="bottom">
                    <el-icon class="action-icon" @click="handToEdit(ite)"><Edit /></el-icon>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
                    <el-icon class="action-icon" @click="handToDelete(item, ite)"><Delete /></el-icon>
                  </el-tooltip>
                </div>
              </div>
              <div class="load-more" @click="nextPage(item)" v-if="item.list && item.list.length < item.envtotal">
                <el-icon><ArrowDown /></el-icon> 加载更多
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 使用Teleport将弹窗传送到body -->
  <Teleport to="body" >
    <!-- 观测截面弹窗 -->
    <div class="add-view" v-if="isAddShow">
      <div class="add-view-header">
        <div class="content-txt1">{{ title }}</div>
        <div @click="clickToClose">
          <el-icon class="close-icon"><CircleClose /></el-icon>
        </div>
      </div>
      <div class="add-view-body">
        <div class="addBox_list_inp">
          <el-input v-model="form.name" type="text" placeholder="名称"></el-input>
        </div>
        <el-input v-model="form.regions" type="textarea" :row="5" resize="none" placeholder="分界线"
          :readonly="true" class="region-textarea"></el-input>
        <div class="edit-actions">
          <div class="edit-action" @click="clickToParentEditLine()">
            编辑<el-icon class="action-icon-inline"><EditPen /></el-icon>
          </div>
          <div class="edit-action" @click="clickToClearLine()">
            清除<el-icon class="action-icon-inline"><Delete /></el-icon>
          </div>
        </div>
        <div class="addBox_list_inp">
          <el-input v-model="form.remark" type="text" placeholder="备注"></el-input>
        </div>
      </div>
      <div class="add-view-footer">
        <el-button type="primary" size="small" @click="clickToSave">保存</el-button>
        <el-button size="small" @click="clickToClose">取消</el-button>
      </div>
    </div>
    
    <!-- 工具 -->
    <div v-if="isToolShow" class="toolsBox">
      <drawTools 
        :isBtn="true"
        @Tools="setTools" 
        @closeTools="clickToToolClear" 
        @subTools="clickToToolSubmit" 
        @addPoint="setAddPoint"
      />
      <div class="btns"></div>
    </div>

    <!-- 类型弹窗 -->
    <el-dialog 
      title="新增" 
      v-model="isAddType" 
      width="30%" 
      :modal="true" 
      :close-on-click-modal="false"
      :append-to-body="true" 
      destroy-on-close
      custom-class="global-dialog"
    >
      <div class="typeBox">
        <div class="typeBox-item">
          <div class="typeBox_title">名称：</div>
          <el-input class="elinp" placeholder="请输入内容" v-model="typeForm.name"></el-input>
        </div>
        <div class="typeBox-item">
          <div class="typeBox_title">key：</div>
          <el-input class="elinp" placeholder="请输入内容（唯一）" v-model="typeForm.envKey"></el-input>
        </div>
        <div class="typeBox-item">
          <div class="typeBox_title">备注：</div>
          <el-input class="elinp" placeholder="请输入内容" v-model="typeForm.remark"></el-input>
        </div>
        <div class="typeBox-item">
          <div class="typeBox_title">排序：</div>
          <el-input class="elinp" type="Number" placeholder="请输入内容" v-model="typeForm.sort"></el-input>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeType">取 消</el-button>
          <el-button type="primary" @click="submitType">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 规则弹窗 -->
    <el-dialog 
      :title="ruleTitle + '规则设置'" 
      v-model="isrule" 
      width="50%" 
      :modal="true"
      :close-on-click-modal="false"
      :append-to-body="true" 
      @close="isrule = false"
      destroy-on-close
      custom-class="global-dialog"
    >
      <ruleVue 
        :ruleData="ruleData" 
        :ruleTitle="ruleTitle"
        v-if="isrule" 
      />
    </el-dialog>
  </Teleport>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick, onBeforeUnmount } from 'vue';
import drawTools from "./drawingTools.vue";
import ruleVue from "./rule.vue";
import { Place } from "@/utils/request.js";
import {
  envType,
  envTypeList,
  env,
  envList,
  delEnv,
  editEnv,
} from "@/api/map/map.js";
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { 
  ArrowRight, 
  ArrowDown, 
  Setting, 
  Plus, 
  Edit, 
  Delete, 
  CircleClose, 
  EditPen,
  Refresh,
  RefreshRight
} from '@element-plus/icons-vue';
import emitter from '@/utils/bus';
import mapUtils from '@/utils/mapUtils';
import { Style, Fill, Stroke } from 'ol/style.js';
import { Feature } from 'ol';
import * as olGeom from 'ol/geom.js';

// 声明全局类型
declare global {
  interface Window {
    T: any;
  }
}

/**
 * 颜色工具函数 - 确保填充颜色有50%的透明度
 * @param color 输入的颜色 (hex, rgb, rgba)
 * @returns 带50%透明度的rgba颜色
 */
function ensureColorWithOpacity(color: string | null): string {
  if (!color) return 'rgba(64, 158, 255, 0.5)'; // 默认蓝色，50%透明
  
  // 已经是rgba格式，修改透明度为0.5
  if (color.startsWith('rgba')) {
    // 提取 rgba 中的 r, g, b 值
    const match = color.match(/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*[\d.]+\s*\)/);
    if (match) {
      const [, r, g, b] = match;
      return `rgba(${r}, ${g}, ${b}, 0.5)`;
    }
  }
  
  // rgb格式转rgba
  if (color.startsWith('rgb(')) {
    // 提取 rgb 中的 r, g, b 值
    const match = color.match(/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/);
    if (match) {
      const [, r, g, b] = match;
      return `rgba(${r}, ${g}, ${b}, 0.5)`;
    }
  }
  
  // 十六进制格式转rgba
  if (color.startsWith('#')) {
    let r = 0, g = 0, b = 0;
    // #RGB 格式
    if (color.length === 4) {
      r = parseInt(color[1] + color[1], 16);
      g = parseInt(color[2] + color[2], 16);
      b = parseInt(color[3] + color[3], 16);
    } 
    // #RRGGBB 格式
    else if (color.length === 7) {
      r = parseInt(color.substring(1, 3), 16);
      g = parseInt(color.substring(3, 5), 16);
      b = parseInt(color.substring(5, 7), 16);
    }
    return `rgba(${r}, ${g}, ${b}, 0.5)`;
  }
  
  // 其他情况，返回默认颜色
  return 'rgba(64, 158, 255, 0.5)';
}

interface EnvItem {
  id: number;
  name: string;
  envKey?: string;
  envType?: string;
  remark?: string;
  sort?: number;
  regions?: string;
  isActive?: boolean;
  list?: EnvDetailItem[];
  envtotal?: number;
  page?: number;
  [key: string]: any;
}

interface EnvDetailItem {
  id: number;
  name: string;
  regions: string;
  envName?: string;
  remark?: string;
  envType?: string;
  [key: string]: any;
}

interface EnvirData {
  title: string;
  type: string;
  remark: string;
  [key: string]: any;
}

interface FormData {
  id?: number;
  name: string;
  regions: string;
  remark?: string;
  envType?: string;
  [key: string]: any;
}

interface TypeForm {
  name: string;
  envKey: string;
  remark?: string;
  sort?: number;
  [key: string]: any;
}

interface MapObject {
  // 通用地图方法
  panTo?: (point: any) => void;
  getCenter?: () => any;
  getSize?: () => { width: number; height: number };
  
  // 天地图特有方法
  addOverLay?: (overlay: any) => void;
  removeOverLay?: (overlay: any) => void;
  setViewport?: (points: any[]) => void;
  
  // OpenLayers特有方法
  addInteraction?: (interaction: any) => void;
  removeInteraction?: (interaction: any) => void;
  addOverlay?: (overlay: any) => void;
  removeOverlay?: (overlay: any) => void;
  on?: (eventType: string, listener: Function) => void;
  un?: (eventType: string, listener: Function) => void;
  
  // 其他任意属性
  [key: string]: any;
}

// GeoJSON相关类型定义
interface GeoPoint {
  type: string;
  coordinates: [number, number];
}

interface GeoLineString {
  type: string;
  coordinates: [number, number][];
}

interface GeoPolygon {
  type: string;
  coordinates: [number, number][][];
}

interface GeoMultiPolygon {
  type: string;
  coordinates: [number, number][][][];
}

type GeoJSON = GeoPoint | GeoLineString | GeoPolygon | GeoMultiPolygon;

// 定义props和emits
const props = defineProps<{
  map: MapObject | null;
}>();

const emit = defineEmits([
  'popupRightVal',
  'clearLine',
  'leftContent',
  'envType',
  'handToClose',
  'renewData',
  'refleshMap',
  'LineToFun',
  'addPointLine',
  'updateList'
]);

// 组件数据
const place = ref<number>(Place);
const activeNames = ref<string | string[]>('');
const datalist = ref<EnvItem[]>([]);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  isFence: 1,
});
const total = ref(0);
const isAddShow = ref(false);
const isToolShow = ref(false);
const title = ref("");
const form = reactive<FormData>({
  name: "",
  regions: "",
  remark: "",
  borderType: null,
  borderColor: null,
  fillColor: null,
  borderWidth: null,
  points: [],
});
const onData = reactive<EnvItem>({} as EnvItem);
const isEdit = ref(false);
const marker = ref<any>(null);
const isAddBtn = ref(false);
const isAddType = ref(false);
const typeForm = reactive<TypeForm>({
  name: "",
  envKey: "",
  remark: "",
  sort: 0,
});
const isrule = ref(false);
const ruleData = ref<any>(null);
const ruleTitle = ref("");
const envirShow = ref(false);
const envirData = reactive<EnvirData>({
  title: "",
  type: "",
  remark: "",
});
const tranLeft = ref("100px");
const tranTop = ref("100px");
const listPolygons = ref<any[]>([]);
const listMark = ref<any[]>([]);
const markObj = ref<any>(null);
const isAutoBtn = ref(false);
const polyline = ref<any>(null);
const pointArr = ref<any[]>([]);
const polylineList = ref<any[]>([]);
const autoMarkerlist = ref<any[]>([]);
const autoMarker = ref<any>(null);
const polygonArry = ref<any[]>([]);
const makers = ref<any[]>([]);
const earlyMakers = ref<any[]>([]);
const envParams = reactive({
  envType: null,
  pageNum: 1,
  pageSize: 10,
  envTypeId: null,
});
const tools = reactive({
  borderColor: "#409EFF", //线框颜色
  borderWidth: 1,
  isSolid: true,
  paddColor: null,
});
const polygon = ref<any>(null);
const handler = ref<any>(null);
const envs = ref<any[]>([]);
const draw = ref<any>(null);
const dialogVisible = ref(false);
const tipDisplay = ref(false);
const curPosList = ref<any[]>([]);
const formData = ref({ name: '' });

// 获取全部通航环境列表
const getwholeEnv = () => {
  envList({
    place: place.value,
  }).then((res: any) => {
    if (res.code == 200) {
      envs.value = res.rows;
      setEarlyWarning(envs.value);
    }
  }).catch(error => {
    console.error("获取全部环境列表失败:", error);
  });
};

// 生命周期钩子
onMounted(() => {
  place.value = Place;
  activeNames.value = [];
  
  // 检查图标字体是否正确加载
  const iconStyle = document.createElement('link');
  iconStyle.rel = 'stylesheet';
  iconStyle.href = '/iconfont/iconfont.css'; // 根据实际路径调整
  document.head.appendChild(iconStyle);
  
  // 初始化页面数据
  getEnvTypeList();
  
  // 直接加载所有通航环境列表，用于绘制电子围栏
  getwholeEnv();
});

// 监听地图变化
watch(() => props.map, (newVal) => {
  if (newVal) {
    // 地图实例加载完成后，初始化地图数据
    initMapData();
  }
  
  if (newVal && earlyMakers.value.length > 0) {
    earlyMakers.value.forEach((ele) => {
      try {
        // 移除图形要素，区分不同类型的对象
        if (ele instanceof Feature) {
          // 如果是OpenLayers Feature
          const source = mapUtils.getVectorSource();
          if (source) {
            source.removeFeature(ele);
          }
        } else if (newVal && typeof newVal.removeOverlay === 'function') {
          // 如果是OpenLayers Overlay
          newVal.removeOverlay(ele);
        } else if (newVal && typeof newVal.removeOverLay === 'function') {
          // 如果是天地图Overlay
          newVal.removeOverLay(ele);
        }
      } catch (error) {
        console.error('移除图形失败:', error);
      }
    });
    // 清空数组
    earlyMakers.value = [];
  }
});

// 组件卸载前
onBeforeUnmount(() => {
  // 清除所有临时图形和绘制工具
  try {
    // 1. 清除所有使用mapUtils添加的图形
    if (makers.value.length > 0) {
      makers.value.forEach((ele) => {
        try {
          if (ele instanceof Feature) {
            const source = mapUtils.getVectorSource();
            if (source) {
              source.removeFeature(ele);
            }
          } else if (props.map && typeof props.map.removeOverlay === 'function') {
            props.map.removeOverlay(ele);
          } else if (props.map && typeof props.map.removeOverLay === 'function') {
            props.map.removeOverLay(ele);
          }
        } catch (error) {
          console.error('移除图形失败:', error);
        }
      });
      makers.value = [];
    }
    
    // 2. 清除earlyMakers中的图形
    if (earlyMakers.value.length > 0) {
      earlyMakers.value.forEach((ele) => {
        try {
          if (ele instanceof Feature) {
            const source = mapUtils.getVectorSource();
            if (source) {
              source.removeFeature(ele);
            }
          } else if (props.map && typeof props.map.removeOverlay === 'function') {
            props.map.removeOverlay(ele);
          } else if (props.map && typeof props.map.removeOverLay === 'function') {
            props.map.removeOverLay(ele);
          }
        } catch (error) {
          console.error('移除图形失败:', error);
        }
      });
      earlyMakers.value = [];
    }
    
    // 3. 移除事件监听器
    if (props.map && typeof props.map.un === 'function') {
      props.map.un('pointermove', handleMapPointerMove);
    }
    
    // 4. 强制清除所有可能残留的矩形工具
    if (window.T) {
      // 搜索并清除地图上所有的矩形元素
      const allOverlays = props.map && props.map.getOverlays ? props.map.getOverlays() : [];
      if (Array.isArray(allOverlays)) {
        allOverlays.forEach((overlay: any) => {
          if (overlay instanceof window.T.Rectangle || 
              overlay instanceof window.T.RectangleTool ||
              (overlay.CLASS_NAME && (
                overlay.CLASS_NAME.includes('Rectangle') || 
                overlay.CLASS_NAME.includes('RectangleTool')
              ))) {
            props.map.removeOverlay(overlay);
          }
        });
      }
      
      // 清除矢量图层中的矩形
      const vectorSource = mapUtils.getVectorSource();
      if (vectorSource) {
        const features = vectorSource.getFeatures();
        features.forEach((feature: any) => {
          const geometry = feature.getGeometry();
          if (geometry && geometry.getType() === 'Polygon') {
            // 检查是否是矩形 (4个点的多边形可能是矩形)
            const coordinates = geometry.getCoordinates()[0];
            if (coordinates && coordinates.length === 5) { // 矩形有5个点 (首尾点相同)
              vectorSource.removeFeature(feature);
            }
          }
        });
      }
    }
  } catch (error) {
    console.error('组件卸载时清理资源失败:', error);
  }
});

// 初始化地图数据
const initMapData = () => {
  // 获取全部通航环境列表进行展示
  getwholeEnv();
  
  // 确保已获取环境类型列表并展开第一个
  if (datalist.value.length === 0) {
    getEnvTypeList();
  } else if (datalist.value.length > 0 && !activeNames.value) {
    // 默认展开第一个环境类型
    const firstItem = datalist.value[0];
    changeCollapse(firstItem);
  }
};

// 方法
const load = () => {
  // 加载更多环境类型
  if (datalist.value.length < total.value) {
    queryParams.pageNum += 1;
    getEnvTypeList();
  }
};

// 获取环境类型
const getEnvTypeList = () => {
  // 记住当前激活的菜单项ID
  const currentActiveId = activeNames.value;
  
  envTypeList(queryParams).then((res: any) => {
    if (res.code == 200) {
      // 处理每个环境类型
      res.rows.forEach((ele: EnvItem) => {
        // 如果是之前激活的项，保持其激活状态
        ele.isActive = ele.id.toString() === currentActiveId;
        ele.list = [];
        ele.envtotal = 0;
        ele.page = 1;
      });
      
      datalist.value = res.rows;
      total.value = res.total;
      emit('envType', datalist.value);
      
      // 如果有之前激活的项，则重新加载该项的子项
      if (currentActiveId && datalist.value.length > 0) {
        const activeItem = datalist.value.find(item => item.id.toString() === currentActiveId);
        if (activeItem) {
          activeNames.value = currentActiveId; // 确保折叠面板状态正确
          getenvList(activeItem);
        }
      }
      // 如果没有激活项但有数据，则默认展开第一项
      else if (datalist.value.length > 0 && !activeNames.value) {
        const firstItem = datalist.value[0];
        changeCollapse(firstItem);
      }
    }
  }).catch((err: any) => {
    console.error("获取环境类型列表失败:", err);
    ElMessage.error("获取类型列表失败，请稍后重试");
  });
};

// 根据环境类型获取环境列表
const getenvList = (val: EnvItem) => {
  if (!val.list) {
    val.list = [];
  }
  
  // 显示加载中状态
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  // 记录当前数据长度，用于避免重复数据
  const currentLength = val.list.length;
  
  const data = {
    envTypeId: val.id,
    pageNum: val.page || 1,
    pageSize: 10,
  };
  
  return envList(data).then((res: any) => {
    if (res.code == 200) {
      // 创建已有ID集合，用于去重
      const existingIds = new Set(val.list.map(item => item.id));
      
      if (val.page === 1) {
        // 第一页直接替换
        val.list = res.rows;
      } else {
        // 不是第一页，确保不重复添加数据
        // 过滤掉已有的数据（根据id去重）
        const newItems = res.rows.filter(item => !existingIds.has(item.id));
        val.list.push(...newItems);
      }
      
      val.envtotal = res.total;
      val.list = [...val.list]; // 触发响应式更新
      
      // 在加载后立即绘制已有围栏
      if (val.list && val.list.length > 0 && props.map) {
        // 只绘制新加载的数据
        const itemsToRender = val.page === 1 ? val.list : res.rows.filter(item => !existingIds.has(item.id));
        drawEnvironmentFences(itemsToRender);
      }
    }
    loading.close(); // 关闭加载状态
  }).catch(error => {
    loading.close(); // 出错时也要关闭加载状态
    console.error("获取环境列表失败:", error);
    ElMessage.error("获取列表失败，请稍后重试");
  });
};

// 绘制已有的环境围栏
const drawEnvironmentFences = (fences: EnvDetailItem[]) => {
  try {
    fences.forEach(fence => {
      if (fence.regions) {
        try {
          const points = JSON.parse(fence.regions);
          
          if (points && points.length > 0) {
            // 为每个点集创建多边形
            for (let j = 0; j < points.length; j++) {
              // 检查点集有效性
              if (!points[j] || !Array.isArray(points[j])) continue;
              
              const coordinates = points[j].map((p: any) => [p.lng, p.lat]);
              
              // 明确解析边框类型
              const lineDash = fence.borderType === 2 ? [5, 5] : undefined;
              
              // 创建多边形样式
              const polygonStyle = new Style({
                fill: new Fill({
                  color: ensureColorWithOpacity(fence.fillColor)
                }),
                stroke: new Stroke({
                  color: ensureColorWithOpacity(fence.borderColor),
                  width: fence.borderWidth || 2,
                  lineDash: lineDash
                })
              });
              
              // 创建多边形要素
              const polygonFeature = new Feature({
                geometry: new olGeom.Polygon([coordinates])
              });
              polygonFeature.setStyle(polygonStyle);
              
              // 将当前项的数据存储在要素的属性中
              polygonFeature.set('envData', {
                title: fence.name,
                type: fence.envName || (typeof fence.envType === 'number' ? setenvType(fence.envType) : (fence.envType ? setenvType(Number(fence.envType)) : '')),
                remark: fence.remark
              });
              
              // 标记为持久化的围栏
              polygonFeature.set('isPersistent', true);
              polygonFeature.set('fenceData', fence);
              
              // 添加到图层
              mapUtils.addFeature(polygonFeature);
              earlyMakers.value.push(polygonFeature);
            }
          }
        } catch (error) {
          console.error("解析围栏区域数据失败:", error);
        }
      }
    });
  } catch (error) {
    console.error("绘制环境围栏失败:", error);
  }
};

// 修改折叠状态
const changeCollapse = (val: EnvItem) => {
  // 检查当前项是否已在activeNames中
  const isActive = activeNames.value === val.id.toString();
  
  if (isActive) {
    // 如果当前已处于激活状态，则关闭
    activeNames.value = '';
    val.isActive = false;
  } else {
    // 如果当前未激活，则打开并获取子项数据
    // 先关闭其他可能处于激活状态的项
    datalist.value.forEach(item => {
      if (item.id !== val.id) {
        item.isActive = false;
      }
    });
    
    // 激活当前项
    // activeNames.value = val.id.toString();
    // val.isActive = true;
    
    // 设置当前环境类型ID
    envParams.envTypeId = val.id;
    
    // 每次展开时获取最新数据
    if (!val.list || val.list.length === 0) {
      val.page = 1; // 重置页码
      getenvList(val);
    }
  }
};

// 加载下一页
const nextPage = (val: EnvItem) => {
  if (val.page) {
    // 检查是否已经加载完所有数据
    if (val.list && val.list.length >= val.envtotal) {
      ElMessage.info("已加载全部数据");
      return;
    }
    
    val.page += 1;
    getenvList(val);
  }
};

// 添加环境
const handToAdd = (val: EnvItem) => {
  reset();
  onData.envKey = val.envKey;
  
  if (polyline.value) {
    props.map?.removeOverLay(polyline.value);
  }
  
  form.name = "";
  form.regions = "";
  form.remark = "";
  form.envTypeId = val.id;
  form.envType = val.envKey;
  
  title.value = "新增" + val.name;
  isAddShow.value = true;
  isToolShow.value = false;
  isAddBtn.value = false;
};

// 关闭添加弹窗
const clickToClose = () => {
  reset();
  
  // 清理临时标记和绘制的围栏
  clearTemporaryFeaturesOnly();
  
  // 移除所有临时添加的多边形
  if (polygon.value) {
    try {
      if (polygon.value instanceof Feature) {
        const source = mapUtils.getVectorSource();
        if (source) {
          source.removeFeature(polygon.value);
        }
      } else if (props.map && typeof props.map.removeOverlay === 'function') {
        props.map.removeOverlay(polygon.value);
      } else if (props.map && typeof props.map.removeOverLay === 'function') {
        props.map.removeOverLay(polygon.value);
      }
      polygon.value = null;
    } catch (error) {
      console.error('移除多边形失败:', error);
    }
  }
  
  // 同样处理绘制工具
  if (handler.value) {
    try {
      if (typeof handler.value.close === 'function') {
        handler.value.close();
      } else if (props.map && typeof props.map.removeInteraction === 'function') {
        props.map.removeInteraction(handler.value);
      }
      handler.value = null;
    } catch (error) {
      console.error('关闭绘图工具失败:', error);
    }
  }
  
  // 清除绘图状态
  isToolShow.value = false;
  isAddShow.value = false;
  
  // 重置表单数据
  form.regions = "";
  form.name = "";
  form.remark = "";
  form.points = [];
  
  // 通知父组件清除线条
  emit('clearLine');
};

// 只清理临时图形，保留持久化的围栏
const clearTemporaryFeaturesOnly = () => {
  // 清理makers中的临时标记
  if (makers.value.length > 0) {
    makers.value.forEach((ele) => {
      try {
        // 移除图形要素，区分不同类型的对象
        if (ele instanceof Feature) {
          // 如果是OpenLayers Feature
          const source = mapUtils.getVectorSource();
          if (source) {
            source.removeFeature(ele);
          }
        } else if (props.map && typeof props.map.removeOverlay === 'function') {
          // 如果是OpenLayers Overlay
          props.map.removeOverlay(ele);
        } else if (props.map && typeof props.map.removeOverLay === 'function') {
          // 如果是天地图Overlay
          props.map.removeOverLay(ele);
        }
      } catch (error) {
        console.error('移除图形失败:', error);
      }
    });
    makers.value = [];
  }
  
  // 清理earlyMakers中非持久化的要素
  if (earlyMakers.value.length > 0) {
    const persistentFeatures: any[] = [];
    
    earlyMakers.value.forEach((ele) => {
      try {
        // 检查是否为临时要素（非持久化）
        if (ele instanceof Feature && ele.get('isPersistent') === false) {
          // 移除临时要素
          const source = mapUtils.getVectorSource();
          if (source) {
            source.removeFeature(ele);
          }
        } else {
          // 保留持久化要素
          persistentFeatures.push(ele);
        }
      } catch (error) {
        console.error('处理图形要素失败:', error);
        // 如果处理过程出错，默认保留该要素
        persistentFeatures.push(ele);
      }
    });
    
    // 更新earlyMakers，只保留持久化要素
    earlyMakers.value = persistentFeatures;
  }
  
  // 清理多边形引用
  if (polygon.value) {
    try {
      if (polygon.value instanceof Feature) {
        // 如果是OpenLayers Feature
        const source = mapUtils.getVectorSource();
        if (source) {
          source.removeFeature(polygon.value);
        }
      } else if (props.map && typeof props.map.removeOverlay === 'function') {
        // 如果是OpenLayers Overlay
        props.map.removeOverlay(polygon.value);
      } else if (props.map && typeof props.map.removeOverLay === 'function') {
        // 如果是天地图Overlay
        props.map.removeOverLay(polygon.value);
      }
      polygon.value = null;
    } catch (error) {
      console.error('移除多边形失败:', error);
    }
  }
};

// 重置表单
const reset = () => {
  tools.borderColor = "#409EFF";
  tools.borderWidth = 1;
  tools.isSolid = true;
  tools.paddColor = null;
  form.points = [];
};

// 编辑线
const clickToParentEditLine = () => {
  isToolShow.value = true;
  isAddShow.value = false;
  
  if (isEdit.value && form.regions) {
    emit('LineToFun', form.regions);
  } else if (!form.line) {
    clickToEditLine();
  }
};

// 编辑线工具
const clickToEditLine = () => {
  if (handler.value) {
    try {
      if (typeof handler.value.close === 'function') {
        handler.value.close();
      } else if (props.map && typeof props.map.removeInteraction === 'function') {
        props.map.removeInteraction(handler.value);
      }
    } catch (error) {
      console.error('关闭绘图工具失败', error);
    }
  }
  
  if (!props.map) return;
  
  try {
    // 使用表单中设置的样式，如果没有则使用默认值
    const fillColor = ensureColorWithOpacity(form.fillColor || tools.paddColor);
    const borderColor = form.borderColor || tools.borderColor || '#409EFF';
    const borderWidth = form.borderWidth || tools.borderWidth || 2;
    const isSolid = form.borderType ? form.borderType === 1 : tools.isSolid;
    
    // 创建绘制样式
    const drawStyle = new Style({
      fill: new Fill({
        color: fillColor
      }),
      stroke: new Stroke({
        color: borderColor,
        width: borderWidth,
        lineDash: isSolid ? undefined : [5, 5]
      })
    });
    
    // 创建绘制交互
    handler.value = mapUtils.createDrawInteraction('Polygon', drawStyle);
    
    if (handler.value) {
      // 添加交互到地图 - 检查方法存在
      if (typeof props.map.addInteraction === 'function') {
        props.map.addInteraction(handler.value);
        
        // 绘制完成事件监听
        handler.value.on('drawend', (e) => {
          isAddShow.value = true;
          
          try {
            // 获取绘制的多边形坐标
            const geometry = e.feature.getGeometry();
            const coordinates = geometry.getCoordinates()[0];
            
            // 将坐标转换为需要的格式
            const points = coordinates.map(coord => ({
              lng: coord[0],
              lat: coord[1]
            }));
            
            form.points.push(points);
            form.regions = JSON.stringify(form.points);
            
            // 确保form中的样式属性被正确设置
            form.borderColor = borderColor;
            form.borderWidth = borderWidth;
            form.borderType = isSolid ? 1 : 2;
            form.fillColor = fillColor;
            
            // 创建多边形样式，确保使用正确的样式设置
            const polygonStyle = new Style({
              fill: new Fill({
                color: fillColor
              }),
              stroke: new Stroke({
                color: borderColor,
                width: borderWidth,
                lineDash: isSolid ? undefined : [5, 5]
              })
            });
            
            // 创建多边形要素
            const polygonFeature = new Feature({
              geometry: new olGeom.Polygon([coordinates])
            });
            polygonFeature.setStyle(polygonStyle);
            
            // 添加到地图
            mapUtils.addFeature(polygonFeature);
            
            // 标记为临时围栏（非持久化）
            polygonFeature.set('isPersistent', false);
            
            // 保存引用以便后续清除
            polygon.value = polygonFeature;
            makers.value.push(polygonFeature);
            
            // 移除绘制交互
            if (typeof props.map.removeInteraction === 'function') {
              props.map.removeInteraction(handler.value);
            }
          } catch (error) {
            console.error('处理绘制结果失败', error);
          }
        });
      } else {
        console.error('地图实例不支持添加交互');
      }
    }
  } catch (error) {
    console.error('创建绘图工具失败', error);
  }
};

// 清除线
const clickToClearLine = () => {
  form.regions = "";
  emit('clearLine');
};

// 清除工具
const clickToToolClear = () => {
  reset();
  if (makers.value.length > 0) {
    makers.value.forEach((ele) => {
      try {
        // 移除图形要素，区分不同类型的对象
        if (ele instanceof Feature) {
          // 如果是OpenLayers Feature
          const source = mapUtils.getVectorSource();
          if (source) {
            source.removeFeature(ele);
          }
        } else if (props.map && typeof props.map.removeOverlay === 'function') {
          // 如果是OpenLayers Overlay
          props.map.removeOverlay(ele);
        } else if (props.map && typeof props.map.removeOverLay === 'function') {
          // 如果是天地图Overlay
          props.map.removeOverLay(ele);
        }
      } catch (error) {
        console.error('移除图形失败:', error);
      }
    });
    makers.value = [];
  }
  
  if (handler.value) {
    try {
      if (typeof handler.value.close === 'function') {
        handler.value.close();
      } else if (props.map && typeof props.map.removeInteraction === 'function') {
        props.map.removeInteraction(handler.value);
      }
    } catch (error) {
      console.error('关闭绘图工具失败:', error);
    }
  }
  
  isToolShow.value = false;
  isAddShow.value = true;
  emit('clearLine');
};

// 提交工具
const clickToToolSubmit = (val: string) => {
  form.regions = val;
  isToolShow.value = false;
  isAddShow.value = true;
  
  const list = form.points;
  const lists = [];
  
  if (list && list.length > 0) {
    for (let i = 0; i < list.length; i++) {
      lists.push(list[i].lat, list[i].lng);
    }
  }
  
  form.borderColor = tools.borderColor;
  form.borderType = tools.isSolid ? 1 : 2;
  form.fillColor = tools.paddColor;
  form.borderWidth = tools.borderWidth;
};

// 保存环境
const clickToSave = () => {
  if (!form.name) {
    ElMessage.error("请填写名称");
    return;
  }
  if (!form.regions) {
    ElMessage.error("请绘制分界线");
    return;
  }
  
  if (!form.id && form.id != 0) {
    form.isFence = true;
    form.place = place.value;
    if (onData.envKey == "shipping_lane") {
      form.display = false;
    }
    
    env(form).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success("新增成功");
        isAddShow.value = false;
        isToolShow.value = false;
        reset();
        if (onData && onData.id) {
          getenvList(onData);
        }
        
        // 将新保存的围栏添加到地图上并保存到earlyMakers以便持久化
        try {
          if (polygon.value) {
            // 清理临时的多边形
            if (polygon.value instanceof Feature) {
              const source = mapUtils.getVectorSource();
              if (source) {
                source.removeFeature(polygon.value);
              }
            } else if (props.map && typeof props.map.removeOverlay === 'function') {
              props.map.removeOverlay(polygon.value);
            } else if (props.map && typeof props.map.removeOverLay === 'function') {
              props.map.removeOverLay(polygon.value);
            }
          }
          
          // 解析坐标并创建持久化的多边形
          if (form.regions) {
            const points = JSON.parse(form.regions);
            if (points && points.length > 0) {
              // 创建持久化的多边形
              if (points[0] && Array.isArray(points[0])) {
                // 为OpenLayers创建多边形Feature
                for (let j = 0; j < points.length; j++) {
                  const coordinates = points[j].map((p: any) => [p.lng, p.lat]);
                  
                  // 明确解析边框类型
                  const lineDash = form.borderType === 2 ? [5, 5] : undefined;
                  
                  // 创建多边形样式
                  const polygonStyle = new Style({
                    fill: new Fill({
                      color: ensureColorWithOpacity(form.fillColor)
                    }),
                    stroke: new Stroke({
                      color: ensureColorWithOpacity(form.borderColor),
                      width: form.borderWidth || 2,
                      lineDash: lineDash
                    })
                  });
                  
                  // 创建多边形要素
                  const polygonFeature = new Feature({
                    geometry: new olGeom.Polygon([coordinates])
                  });
                  polygonFeature.setStyle(polygonStyle);
                  
                  // 将当前项的数据存储在要素的属性中
                  polygonFeature.set('envData', {
                    title: form.name,
                    type: setenvType(form.envTypeId),
                    remark: form.remark
                  });
                  
                  // 标记为持久化的围栏
                  polygonFeature.set('isPersistent', true);
                  polygonFeature.set('fenceData', form);
                  
                  // 添加到图层
                  mapUtils.addFeature(polygonFeature);
                  earlyMakers.value.push(polygonFeature);
                }
              }
            }
          }
        } catch (error) {
          console.error('围栏持久化失败:', error);
        }
        
        emit('renewData', 'leftContent');
      }
    }).catch(error => {
      console.error(error);
      ElMessage.error("保存失败: " + (error.message || "未知错误"));
    });
  } else {
    editEnv(form).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success("编辑成功");
        isAddShow.value = false;
        isToolShow.value = false;
        reset();
        if (onData && onData.id) {
          getenvList(onData);
        }
        
        // 将编辑后的围栏添加到地图上并保存到earlyMakers以便持久化
        try {
          if (polygon.value) {
            // 清理临时的多边形
            if (polygon.value instanceof Feature) {
              const source = mapUtils.getVectorSource();
              if (source) {
                source.removeFeature(polygon.value);
              }
            } else if (props.map && typeof props.map.removeOverlay === 'function') {
              props.map.removeOverlay(polygon.value);
            } else if (props.map && typeof props.map.removeOverLay === 'function') {
              props.map.removeOverLay(polygon.value);
            }
          }
          
          // 解析坐标并创建持久化的多边形
          if (form.regions) {
            const points = JSON.parse(form.regions);
            if (points && points.length > 0) {
              // 创建持久化的多边形
              if (points[0] && Array.isArray(points[0])) {
                // 为OpenLayers创建多边形Feature
                for (let j = 0; j < points.length; j++) {
                  const coordinates = points[j].map((p: any) => [p.lng, p.lat]);
                  
                  // 明确解析边框类型
                  const lineDash = form.borderType === 2 ? [5, 5] : undefined;
                  
                  // 创建多边形样式
                  const polygonStyle = new Style({
                    fill: new Fill({
                      color: ensureColorWithOpacity(form.fillColor)
                    }),
                    stroke: new Stroke({
                      color: ensureColorWithOpacity(form.borderColor),
                      width: form.borderWidth || 2,
                      lineDash: lineDash
                    })
                  });
                  
                  // 创建多边形要素
                  const polygonFeature = new Feature({
                    geometry: new olGeom.Polygon([coordinates])
                  });
                  polygonFeature.setStyle(polygonStyle);
                  
                  // 将当前项的数据存储在要素的属性中
                  polygonFeature.set('envData', {
                    title: form.name,
                    type: setenvType(form.envTypeId),
                    remark: form.remark
                  });
                  
                  // 标记为持久化的围栏
                  polygonFeature.set('isPersistent', true);
                  polygonFeature.set('fenceData', form);
                  
                  // 添加到图层
                  mapUtils.addFeature(polygonFeature);
                  earlyMakers.value.push(polygonFeature);
                }
              }
            }
          }
        } catch (error) {
          console.error('围栏持久化失败:', error);
        }
        
        emit('renewData', 'leftContent');
        emit('refleshMap');
      }
    }).catch(error => {
      ElMessage.error("编辑失败: " + (error.message || "未知错误"));
    });
  }
};

// 编辑环境
const handToEdit = (val: EnvDetailItem) => {
  onData.envType = val.envType;
  form.id = val.id;
  form.name = val.name;
  form.regions = val.regions;
  form.remark = val.remark || "";
  form.points = [];
  
  isEdit.value = true;
  isAddShow.value = true;
  title.value = "编辑" + val.name;
};

// 删除环境
const handToDelete = (item: EnvItem, ite: EnvDetailItem) => {
  ElMessageBox.confirm("是否确认删除该数据?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      return delEnv(ite.id);
    })
    .then((res: any) => {
      if (res.code == 200) {
        ElMessage.success("删除成功");
        Object.assign(onData, item);
        envParams.pageNum = 1;
        envParams.envTypeId = item.id;
        getenvList(onData);
        emit('renewData', 'leftContent');
        emit('refleshMap');
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 地图定位中心
const clickToCenterMap = (val: EnvDetailItem) => {
  const T = window.T;
  if (!props.map) return;

  try {
    const points = JSON.parse(val.regions);
    
    if (points && points[0] && points[0][0]) {
      props.map.panTo(new T.LngLat(points[0][0].lng, points[0][0].lat));
    }
    
    setTimeout(() => {
      showEnvirInfo(val);
    }, 500);
  } catch (error) {
    console.error("解析区域数据失败", error);
  }
};

// 设置工具
const setTools = (val: any) => {
  // 更新工具设置
  Object.assign(tools, val);
  
  // 更新表单设置
  form.borderType = val.isSolid ? 1 : 2;
  form.borderWidth = val.borderWidth;
  form.borderColor = val.borderColor;
  form.fillColor = val.paddColor;
  
  // 如果当前正在编辑多边形，实时更新样式
  if (polygon.value) {
    try {
      if (polygon.value instanceof Feature) {
        // 对于OpenLayers Feature，创建新样式并应用
        const polygonStyle = new Style({
          fill: new Fill({
            color: ensureColorWithOpacity(val.paddColor)
          }),
          stroke: new Stroke({
            color: ensureColorWithOpacity(val.borderColor),
            width: val.borderWidth || 2,
            lineDash: val.isSolid ? undefined : [5, 5]
          })
        });
        
        polygon.value.setStyle(polygonStyle);
      } else if (props.map && typeof polygon.value.setColor === 'function') {
        // 对于天地图多边形，使用其API
        polygon.value.setColor(ensureColorWithOpacity(val.borderColor));
        polygon.value.setWeight(val.borderWidth);
        polygon.value.setLineStyle(val.isSolid ? 'solid' : 'dashed');
        polygon.value.setFillColor(ensureColorWithOpacity(val.paddColor));
      }
    } catch (error) {
      console.error('更新多边形样式失败:', error);
    }
  }
  
  // 如果处于绘制模式，重新创建绘制工具以应用新样式
  if (handler.value && typeof props.map?.removeInteraction === 'function') {
    try {
      // 移除当前绘制工具
      props.map.removeInteraction(handler.value);
      
      // 创建新样式
      const drawStyle = new Style({
        fill: new Fill({
          color: ensureColorWithOpacity(val.paddColor)
        }),
        stroke: new Stroke({
          color: ensureColorWithOpacity(val.borderColor),
          width: val.borderWidth || 2,
          lineDash: val.isSolid ? undefined : [5, 5]
        })
      });
      
      // 创建新绘制工具
      handler.value = mapUtils.createDrawInteraction('Polygon', drawStyle);
      
      // 添加到地图
      props.map.addInteraction(handler.value);
      
      // 重新绑定事件
      handler.value.on('drawend', (e) => {
        isAddShow.value = true;
        
        try {
          // 获取绘制的多边形坐标
          const geometry = e.feature.getGeometry();
          const coordinates = geometry.getCoordinates()[0];
          
          // 将坐标转换为需要的格式
          const points = coordinates.map(coord => ({
            lng: coord[0],
            lat: coord[1]
          }));
          
          form.points.push(points);
          form.regions = JSON.stringify(form.points);
          
          // 创建多边形样式
          const polygonStyle = new Style({
            fill: new Fill({
              color: ensureColorWithOpacity(val.paddColor)
            }),
            stroke: new Stroke({
              color: ensureColorWithOpacity(val.borderColor),
              width: val.borderWidth || 2,
              lineDash: val.isSolid ? undefined : [5, 5]
            })
          });
          
          // 创建多边形要素
          const polygonFeature = new Feature({
            geometry: new olGeom.Polygon([coordinates])
          });
          polygonFeature.setStyle(polygonStyle);
          
          // 标记为临时围栏
          polygonFeature.set('isPersistent', false);
          
          // 添加到地图
          mapUtils.addFeature(polygonFeature);
          
          // 保存引用以便后续清除
          polygon.value = polygonFeature;
          makers.value.push(polygonFeature);
          
          // 移除绘制交互
          if (typeof props.map.removeInteraction === 'function') {
            props.map.removeInteraction(handler.value);
          }
        } catch (error) {
          console.error('处理绘制结果失败', error);
        }
      });
    } catch (error) {
      console.error('更新绘制工具失败:', error);
    }
  }
  
  emit('LineToFun', val);
};

// 设置添加点
const setAddPoint = (val: any) => {
  emit('addPointLine', val);
  
  let arr = val.split(",");
  let newArr = [];
  for (let i = 0; i < arr.length; i += 2) {
    if (arr[i]) {
      let obj = {
        lat: Number(arr[i]),
        lng: Number(arr[i + 1]),
      };
      newArr.push(obj);
    }
  }
  
  if (handler.value) {
    handler.value.close();
  }
  
  form.regions = JSON.stringify([newArr]);
};

// 规则设置
const setrule = (val: EnvItem) => {
  ruleData.value = val;
  ruleTitle.value = val.name;
  isrule.value = true;
};

// 关闭类型弹窗
const closeType = () => {
  typeForm.name = "";
  typeForm.envKey = "";
  typeForm.remark = "";
  typeForm.sort = 0;
  isAddType.value = false;
};

// 提交类型
const submitType = () => {
  if (!typeForm.name) {
    ElMessage.error("请填写名称");
    return;
  }
  if (!typeForm.envKey) {
    ElMessage.error("请填写key");
    return;
  }
  
  envType(typeForm).then((res: any) => {
    if (res.code == 200) {
      ElMessage.success("新增成功");
      closeType();
      datalist.value = [];
      getEnvTypeList();
    }
  });
};

// 绘制通航环境
const setEarlyWarning = (warning: any[]) => {
  if (!props.map) {
    console.error("地图实例未加载，无法绘制环境");
    return;
  }
  
  if (!warning || warning.length === 0) {
    console.warn("没有可绘制的环境数据");
    return;
  }
  
  // 清除已有的环境围栏
  if (earlyMakers.value.length > 0) {
    earlyMakers.value.forEach((ele) => {
      try {
        if (ele instanceof Feature) {
          // 如果是OpenLayers Feature
          const source = mapUtils.getVectorSource();
          if (source) {
            source.removeFeature(ele);
          }
        } else if (props.map && typeof props.map.removeOverlay === 'function') {
          // 如果是OpenLayers Overlay
          props.map.removeOverlay(ele);
        } else if (props.map && typeof props.map.removeOverLay === 'function') {
          // 如果是天地图Overlay
          props.map.removeOverLay(ele);
        }
      } catch (error) {
        console.error('移除早期标记失败:', error);
      }
    });
    earlyMakers.value = [];
  }
  
  const T = window.T;
  
  // 如果T不存在，则使用OpenLayers绘制
  if (!T) {
    try {
      for (let i = 0; i < warning.length; i++) {
        if (warning[i].display && warning[i].regions) {
          try {
            const points = JSON.parse(warning[i].regions);
            
            for (let j = 0; j < points.length; j++) {
              const coordinates = points[j].map((p: any) => [p.lng, p.lat]);
              
              // 创建多边形样式
              const polygonStyle = new Style({
                fill: new Fill({
                  color: ensureColorWithOpacity(warning[i].fillColor)
                }),
                stroke: new Stroke({
                  color: ensureColorWithOpacity(warning[i].borderColor),
                  width: warning[i].borderWidth || 2,
                  lineDash: warning[i].borderType === 1 ? undefined : [5, 5]
                })
              });
              
              // 创建多边形要素
              const polygonFeature = new Feature({
                geometry: new olGeom.Polygon([coordinates])
              });
              polygonFeature.setStyle(polygonStyle);
              
              // 将当前项的数据存储在要素的属性中
              polygonFeature.set('envData', {
                title: warning[i].name,
                type: setenvType(warning[i].envType),
                remark: warning[i].remark
              });
              
              // 添加到图层
              mapUtils.addFeature(polygonFeature);
              earlyMakers.value.push(polygonFeature);
            }
          } catch (error) {
            console.error("解析区域数据失败", error);
          }
        } else if (warning[i].regions2) {
          try {
            const points = JSON.parse(warning[i].regions2);
            
            for (let j = 0; j < points.length; j++) {
              const coordinates = points[j].map((p: any) => [p.lng, p.lat]);
              
              // 创建线条样式
              const lineStyle = new Style({
                stroke: new Stroke({
                  color: ensureColorWithOpacity(warning[i].borderColor),
                  width: warning[i].borderWidth || 2,
                  lineDash: warning[i].borderType === 1 ? undefined : [5, 5]
                })
              });
              
              // 创建线条要素
              const lineFeature = new Feature({
                geometry: new olGeom.LineString(coordinates)
              });
              lineFeature.setStyle(lineStyle);
              
              // 将当前项的数据存储在要素的属性中
              lineFeature.set('envData', {
                title: warning[i].name,
                type: setenvType(warning[i].envType),
                remark: warning[i].remark
              });
              
              // 添加到图层
              mapUtils.addFeature(lineFeature);
              earlyMakers.value.push(lineFeature);
            }
          } catch (error) {
            console.error("解析regions2数据失败", error);
          }
        }
      }
      
      // 为地图添加鼠标悬停事件
      if (props.map && typeof props.map.on === 'function') {
        // 移除之前的事件监听器
        props.map.un('pointermove', handleMapPointerMove);
        // 添加新的事件监听器
        props.map.on('pointermove', handleMapPointerMove);
      }
    } catch (error) {
      console.error("使用OpenLayers绘制环境失败:", error);
    }
    return;
  }
  
  // 天地图绘制方式 (保留原逻辑) 
  for (let i = 0; i < warning.length; i++) {
    if (warning[i].display) {
      try {
        const points = JSON.parse(warning[i].regions);
        const currentItemData = warning[i]; // 保存当前条目数据，避免闭包问题
        
        for (let j = 0; j < points.length; j++) {
          const polygon = new T.Polygon(points, {
            color: ensureColorWithOpacity(currentItemData.borderColor),
            weight: currentItemData.borderWidth,
            fillColor: ensureColorWithOpacity(currentItemData.fillColor),
          });
          
          props.map.addOverLay(polygon);
          earlyMakers.value.push(polygon);
          
          // 鼠标悬停事件 - 使用全局InfoWindow
          polygon.addEventListener("mouseover", (e: any) => {
            emitter.emit('show-info-window', {
              title: currentItemData.name,
              type: setenvType(currentItemData.envType),
              remark: currentItemData.remark,
              x: e.containerPoint.x,
              y: e.containerPoint.y - 10, // 稍微上移避免鼠标遮挡
              autoClose: false
            });
          });
          
          // 鼠标移出事件
          polygon.addEventListener("mouseout", () => {
            emitter.emit('hide-info-window');
          });
        }
      } catch (error) {
        console.error("解析区域数据失败", error);
      }
    } else if (warning[i].regions2) {
      try {
        const points = JSON.parse(warning[i].regions2);
        const currentItemData = warning[i]; // 保存当前条目数据，避免闭包问题
        
        for (let j = 0; j < points.length; j++) {
          const polyline = new T.Polyline(points[j], {
            color: "blue",
            weight: currentItemData.borderWidth,
          });
          
          props.map.addOverLay(polyline);
          earlyMakers.value.push(polyline);
          
          // 鼠标悬停事件 - 使用全局InfoWindow
          polyline.addEventListener("mouseover", (e: any) => {
            emitter.emit('show-info-window', {
              title: currentItemData.name,
              type: setenvType(currentItemData.envType),
              remark: currentItemData.remark,
              x: e.containerPoint.x,
              y: e.containerPoint.y - 10, // 稍微上移避免鼠标遮挡
              autoClose: false
            });
          });
          
          // 鼠标移出事件 - 修复mouseout事件绑定方式
          polyline.addEventListener("mouseout", () => {
            emitter.emit('hide-info-window');
          });
        }
      } catch (error) {
        console.error("解析regions2数据失败", error);
      }
    }
  }
};

// 查询环境类型
const setenvType = (id: number) => {
  let str = "";
  datalist.value.forEach((ele) => {
    if (ele.id == id) {
      str = ele.name;
    }
  });
  return str;
};

// 显示环境信息
const showEnvirInfo = (val: EnvDetailItem) => {
  // 使用事件总线触发全局信息窗口
  emitter.emit('show-info-window', {
    title: val.name,
    type: val.envName || '',
    remark: val.remark || '',
    duration: 5000 // 5秒后自动关闭
  });
};

// OpenLayers鼠标悬停处理函数
const handleMapPointerMove = (e: any) => {
  if (!props.map) return;
  
  // 检查当前指针位置是否有Feature
  const feature = props.map.forEachFeatureAtPixel?.(e.pixel, (feature: any) => feature);
  
  if (feature) {
    // 获取Feature上存储的环境数据
    const envData = feature.get('envData');
    if (envData) {
      // 使用事件总线显示信息窗口
      emitter.emit('show-info-window', {
        ...envData,
        x: e.originalEvent.clientX,
        y: e.originalEvent.clientY - 10, // 稍微上移避免鼠标遮挡
        autoClose: false
      });
    }
  } else {
    // 隐藏信息窗口
    emitter.emit('hide-info-window');
  }
};

/**
 * 打开电子围栏绘制
 */
function clickToEditPolygon() {
  dialogVisible.value = true;
  tipDisplay.value = true;
  curPosList.value = [];
  
  if (draw.value) {
    try {
      if (props.map && props.map.removeInteraction) {
        props.map.removeInteraction(draw.value);
      }
      draw.value = null;
    } catch (error) {
      console.error('移除先前的绘制交互失败:', error);
    }
  }
  
  try {
    // 创建绘制样式
    const drawStyle = new Style({
      fill: new Fill({
        color: ensureColorWithOpacity('#409EFF')
      }),
      stroke: new Stroke({
        color: '#409EFF',
        width: 2
      })
    });
    
    // 创建绘制交互
    draw.value = mapUtils.createDrawInteraction('Polygon', drawStyle);
    
    if (draw.value) {
      // 添加交互到地图
      if (props.map && props.map.addInteraction) {
        props.map.addInteraction(draw.value);
        
        // 绘制完成事件监听
        draw.value.on('drawend', (e) => {
          try {
            // 获取绘制的多边形坐标
            const geometry = e.feature.getGeometry();
            const coordinates = geometry.getCoordinates()[0];
            
            // 将坐标转换为需要的格式
            const points = coordinates.map(coord => ({
              lng: coord[0],
              lat: coord[1]
            }));
            
            // 保存坐标点
            curPosList.value = points;
            
            // 创建多边形要素
            const polygonFeature = new Feature({
              geometry: new olGeom.Polygon([coordinates])
            });
            
            // 设置样式
            polygonFeature.setStyle(drawStyle);
            
            // 添加到地图
            mapUtils.addFeature(polygonFeature);
            
            // 保存要素引用，以便后续删除
            earlyMakers.value.push(polygonFeature);
            
            // 移除绘制交互
            if (props.map && props.map.removeInteraction) {
              props.map.removeInteraction(draw.value);
              draw.value = null;
            }
          } catch (error) {
            console.error('处理绘制结果失败:', error);
          }
        });
      } else {
        console.error('地图实例不支持添加交互');
      }
    }
  } catch (error) {
    console.error('创建绘制工具失败:', error);
  }
}

/**
 * 关闭电子围栏绘制
 */
function clickToClosePolygon() {
  dialogVisible.value = false;
  tipDisplay.value = false;
  curPosList.value = [];
  
  // 清理已绘制的要素
  try {
    // 清除临时多边形（特定针对围栏绘制功能）
    if (earlyMakers.value && earlyMakers.value.length > 0) {
      // 只移除非持久化的要素
      const persistentFeatures: any[] = [];
      const temporaryFeatures: any[] = [];
      
      // 分离持久化和临时要素
      earlyMakers.value.forEach((feature: any) => {
        if (feature instanceof Feature && feature.get('isPersistent') === false) {
          temporaryFeatures.push(feature);
        } else {
          persistentFeatures.push(feature);
        }
      });
      
      // 移除临时要素
      const vectorSource = mapUtils.getVectorSource();
      if (vectorSource) {
        temporaryFeatures.forEach((feature: any) => {
          if (feature instanceof Feature) {
            vectorSource.removeFeature(feature);
          } else if (props.map && typeof props.map.removeOverlay === 'function') {
            props.map.removeOverlay(feature);
          } else if (props.map && typeof props.map.removeOverLay === 'function') {
            props.map.removeOverLay(feature);
          }
        });
      }
      
      // 保留持久化要素
      earlyMakers.value = persistentFeatures;
    }

    // 清除当前多边形引用
    if (polygon.value) {
      const vectorSource = mapUtils.getVectorSource();
      if (vectorSource && polygon.value instanceof Feature) {
        vectorSource.removeFeature(polygon.value);
      } else if (props.map && typeof props.map.removeOverlay === 'function' && !(polygon.value instanceof Feature)) {
        props.map.removeOverlay(polygon.value);
      } else if (props.map && typeof props.map.removeOverLay === 'function' && !(polygon.value instanceof Feature)) {
        props.map.removeOverLay(polygon.value);
      }
      polygon.value = null;
    }

    // 移除绘制交互
    if (props.map && props.map.removeInteraction && draw.value) {
      props.map.removeInteraction(draw.value);
      draw.value = null;
    }
  } catch (error) {
    console.error('移除要素时出错:', error);
  }
}

/**
 * 保存电子围栏
 */
function clickToSavePolygon() {
  if (earlyMakers.value && earlyMakers.value.length > 0) {
    if (curPosList.value.length >= 3) {
      emit('updateList', {
        name: formData.value.name,
        regions: JSON.stringify(curPosList.value)
      });

      // 清理绘制的要素
      try {
        const vectorSource = mapUtils.getVectorSource();
        if (vectorSource) {
          earlyMakers.value.forEach((ele: any) => {
            if (ele instanceof Feature) {
              vectorSource.removeFeature(ele);
            }
          });
        }
        // 清空记录
        earlyMakers.value = [];
      } catch (error) {
        console.error('移除要素时出错:', error);
      }

      dialogVisible.value = false;
      tipDisplay.value = false;
      
      // 移除绘制交互
      if (props.map && props.map.removeInteraction && draw.value) {
        props.map.removeInteraction(draw.value);
        draw.value = null;
      }
    } else {
      ElMessage.warning('请至少绘制三个点');
    }
  } else {
    ElMessage.warning('请先绘制电子围栏');
  }
}

// 刷新所有电子围栏 - 强制刷新方式
const refreshAllFences = () => {
  // 显示加载状态
  const loading = ElLoading.service({
    lock: true,
    text: '正在刷新...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    // 强制清除地图上所有图形元素
    const mapInstance = props.map;
    if (mapInstance) {
      // 1. 清除所有矢量图层中的要素
      const vectorSource = mapUtils.getVectorSource();
      if (vectorSource) {
        vectorSource.clear(); // 清空所有要素
      }

      // 2. 清除所有使用天地图API添加的覆盖物
      if (window.T) {
        try {
          // 天地图有自己的方法清除覆盖物
          if (typeof mapInstance.clearOverLays === 'function') {
            mapInstance.clearOverLays();
          } 
          // 如果没有clearOverLays方法，则手动清除
          else if (typeof mapInstance.getOverLays === 'function') {
            const overlays = mapInstance.getOverLays() || [];
            overlays.forEach((overlay: any) => {
              mapInstance.removeOverLay(overlay);
            });
          }
          // OpenLayers风格的清除
          else if (typeof mapInstance.getOverlays === 'function') {
            const overlays = mapInstance.getOverlays().getArray() || [];
            overlays.forEach((overlay: any) => {
              mapInstance.removeOverlay(overlay);
            });
          }
        } catch (error) {
          console.error('清除覆盖物失败:', error);
        }
      }

      // 2a. 特别检查并清除可能存在的矩形工具
      if (window.T) {
        try {
          // 获取所有可能的矩形工具实例
          const instanceKeys = Object.keys(window.T);
          for (const key of instanceKeys) {
            if (key.includes('Rectangle') || key.includes('rectangle')) {
              // 尝试找到矩形实例并清除
              const instances = document.querySelectorAll('.tdt-Rectangle, .tdt-rectangle, .tdt-RectangleTool');
              instances.forEach(instance => {
                instance.parentNode?.removeChild(instance);
              });
            }
          }
          
          // 获取所有矩形绘制工具并移除它们
          const allOverlays = mapInstance.getOverlays ? mapInstance.getOverlays() : (mapInstance.getOverLays ? mapInstance.getOverLays() : []);
          if (Array.isArray(allOverlays)) {
            allOverlays.forEach((overlay: any) => {
              try {
                // 检查类名或实例类型以确定是否为矩形
                if (overlay instanceof window.T.Rectangle || 
                    overlay instanceof window.T.RectangleTool ||
                    (overlay.CLASS_NAME && (
                      overlay.CLASS_NAME.includes('Rectangle') || 
                      overlay.CLASS_NAME.includes('RectangleTool')
                    ))) {
                  if (typeof mapInstance.removeOverlay === 'function') {
                    mapInstance.removeOverlay(overlay);
                  } else if (typeof mapInstance.removeOverLay === 'function') {
                    mapInstance.removeOverLay(overlay);
                  }
                }
              } catch (err) {
                // 忽略单个删除错误，继续处理其他元素
                console.error('移除单个矩形失败:', err);
              }
            });
          }
        } catch (error) {
          console.error('清除矩形工具失败:', error);
        }
      }

      // 3. 移除所有交互
      if (mapInstance.getInteractions && mapInstance.removeInteraction) {
        const interactions = [...mapInstance.getInteractions().getArray()];
        interactions.forEach(interaction => {
          if (interaction.get('isCustom')) { // 只移除自定义添加的交互
            mapInstance.removeInteraction(interaction);
          }
        });
      }
    }

    // 4. 清空所有引用数组
    earlyMakers.value = [];
    makers.value = [];
    pointArr.value = [];
    polylineList.value = [];
    curPosList.value = [];
    autoMarkerlist.value = [];

    // 5. 清空所有单个引用
    polygon.value = null;
    handler.value = null;
    polyline.value = null;
    draw.value = null;
    marker.value = null;
    autoMarker.value = null;
    markObj.value = null;

    // 6. 重置所有状态
    isAddShow.value = false;
    isToolShow.value = false;
    isAddBtn.value = false;
    isEdit.value = false;
    isAutoBtn.value = false;
    envirShow.value = false;
    dialogVisible.value = false;
    tipDisplay.value = false;

    // 7. 重置表单数据
    form.name = "";
    form.regions = "";
    form.remark = "";
    form.points = [];
    form.borderType = null;
    form.borderColor = null;
    form.fillColor = null;
    form.borderWidth = null;

    // 8. 重置工具设置
    tools.borderColor = "#409EFF";
    tools.borderWidth = 1;
    tools.isSolid = true;
    tools.paddColor = null;

    // 9. 通知父组件清除所有内容
    emit('clearLine');
    emit('refleshMap'); // 通知地图容器刷新

    // 10. 清空数据列表并重新获取
    datalist.value = [];
    activeNames.value = '';
    envs.value = [];
    
    // 11. 隐藏所有信息窗口 
    emitter.emit('hide-info-window');

    // 12. 重新加载所有数据
    setTimeout(() => {
      // 重新初始化页面
      getEnvTypeList();
      getwholeEnv();
      
      // 关闭加载状态
      loading.close();
      ElMessage.success("刷新成功，所有数据已重置");
    }, 500);
  } catch (error) {
    console.error('强制刷新失败:', error);
    loading.close();
    ElMessage.error("刷新失败，正在尝试重载页面...");
    // 直接调用页面重载
    setTimeout(() => {
      window.location.reload();
    }, 1500);
  }
};

// 显示新增环境类型弹窗
const showAddEnvType = () => {
  // 重置环境类型表单
  typeForm.name = "";
  typeForm.envKey = "";
  typeForm.remark = "";
  typeForm.sort = 0;
  
  // 显示新增类型弹窗
  isAddType.value = true;
};

// 强制重载页面
const forceReload = () => {
  ElMessageBox.confirm(
    '确定要强制重载页面吗？这将清除所有未保存的数据。',
    '强制重载',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      window.location.reload();
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 删除主项
const deleteMainItem = (item: EnvItem) => {
  ElMessageBox.confirm("是否确认删除该数据?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
  .then(() => {
    // 确认后调用删除API
    return delEnv(item.id);
  })
  .then((res: any) => {
    if (res.code == 200) {
      ElMessage.success("删除成功");
      // 刷新数据
      getEnvTypeList();
      emit('renewData', 'leftContent');
      emit('refleshMap');
    } else {
      ElMessage.error(res.msg || "删除失败");
    }
  })
  .catch(() => {
    // 取消操作或异常处理
  });
};
</script>
<style>
/* 全局样式 - 在Teleport后应用于整个页面 */
.add-view {
  width: 400px;
  background-color: #ffffff;
  padding: 20px;
  display: flex;
  flex-direction: column;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 2001;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  color: #333333;
}

.toolsBox {
  position: fixed;
  bottom: 60px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 2002;
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid var(--el-border-color-light, #e4e7ed);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.global-dialog {
  background-color: white !important;
  border-radius: 12px !important;
  border: 1px solid var(--el-border-color-light, #e4e7ed) !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
  overflow: hidden !important;
  z-index: 2003 !important;
}

.global-dialog .el-dialog__header {
  background-color: var(--el-bg-color-page, #f5f7fa) !important;
  padding: 15px 20px !important;
  margin-right: 0 !important;
  border-bottom: 1px solid var(--el-border-color-light, #e4e7ed) !important;
}

.global-dialog .el-dialog__title {
  color: var(--el-text-color-primary, #303133) !important;
  font-weight: 600 !important;
}

.global-dialog .el-dialog__body {
  color: var(--el-text-color-primary, #303133) !important;
  padding: 20px !important;
}

.global-dialog .el-dialog__footer {
  padding: 10px 20px 20px !important;
  border-top: 1px solid var(--el-border-color-light, #e4e7ed) !important;
}

.global-dialog .el-dialog__headerbtn .el-dialog__close {
  color: var(--el-text-color-secondary, #909399) !important;
}

.global-dialog .el-dialog__headerbtn:hover .el-dialog__close {
  color: var(--el-color-primary, #409EFF) !important;
}

/* 修复tooltip样式 */
.el-popper.is-dark {
  background-color: var(--el-bg-color-overlay, white) !important;
  border: 1px solid var(--el-border-color-light, #e4e7ed) !important;
  color: var(--el-text-color-primary, #303133) !important;
}

.el-popper.is-dark .el-popper__arrow::before {
  background: var(--el-bg-color-overlay, white) !important;
  border: 1px solid var(--el-border-color-light, #e4e7ed) !important;
}

/* Element Plus弹出层样式优化 */
.el-select-dropdown {
  background-color: var(--el-bg-color-overlay, white) !important;
  border: 1px solid var(--el-border-color-light, #e4e7ed) !important;
}

.el-select-dropdown__item {
  color: var(--el-text-color-primary, #303133) !important;
}

.el-select-dropdown__item.hover, 
.el-select-dropdown__item:hover {
  background-color: var(--el-fill-color-light, #f5f7fa) !important;
}

.el-select-dropdown__item.selected {
  color: var(--el-color-primary, #409EFF) !important;
  font-weight: bold;
}
</style>
<style scoped>
/* 基础样式 */
.left-content-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.content {
  width: 100%;
  height: 100%;
  z-index: 1000;
  display: flex;
  flex-direction: row;
}

.flex-column {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

/* 头部动作栏样式 */
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: var(--el-bg-color-page, #f5f7fa);
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  margin-bottom: 10px;
}

.title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary, #303133);
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.action-icon {
  font-size: 18px;
  color: var(--el-color-primary, #409EFF);
  cursor: pointer;
  transition: all 0.3s;
}

.action-icon:hover {
  color: var(--el-color-primary-light-3);
  transform: scale(1.2);
}

.reload-icon {
  color: var(--el-color-warning, #E6A23C);
}

.reload-icon:hover {
  color: var(--el-color-danger, #F56C6C);
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.3);
  }
  100% {
    transform: scale(1);
  }
}

/* 折叠标题样式 */
.collapse-header {
  padding: 5px 5px 5px 5px;
  background-color: var(--el-bg-color-overlay, white);
  border-radius: 8px;
  display: flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
  border-left: 3px solid var(--el-color-primary, #409EFF);
  transition: all 0.3s;
  margin-bottom: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.collapse-header:hover {
  background-color: var(--el-fill-color-light, #f5f7fa);
}

.collapse-title {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding-left: 10px;
  width: 100%;
}

.collapse-icon {
  margin-right: 10px;
  transition: all 0.3s;
  color: var(--el-color-primary, #409EFF);
  font-size: 18px;
}

.collapse-icon.active {
  transform: rotate(90deg);
}

.envName {
  color: var(--el-text-color-primary, #303133);
  font-size: 15px;
  font-weight: 500;
}

.collapse-actions {
  display: flex;
  gap: 10px;
}

.action-icon-inline {
  font-size: 16px;
  margin-left: 5px;
  color: var(--el-color-primary, #409EFF);
}

/* 环境项样式 */
.envItem {
  padding: 10px 15px;
  margin: 8px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  color: var(--el-text-color-regular, #606266);
  background-color: var(--el-bg-color-overlay, white);
  border-left: 3px solid var(--el-color-primary, #409EFF);
  border-radius: 0 4px 4px 0;
  transition: all 0.3s;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.envItem:hover {
  background-color: var(--el-fill-color-light, #f5f7fa);
  color: var(--el-text-color-primary, #303133);
  transform: translateX(5px);
}

.envItem-name {
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 170px;
}

.envItem-actions {
  display: flex;
}

/* 加载更多样式 */
.load-more {
  text-align: center;
  padding: 8px 0;
  color: var(--el-color-primary, #409EFF);
  cursor: pointer;
  margin-top: 5px;
  font-size: 14px;
  background-color: rgba(64, 158, 255, 0.1);
  border-radius: 4px;
  transition: all 0.3s;
}

.load-more:hover {
  background-color: rgba(64, 158, 255, 0.2);
}

.load-more i {
  margin-right: 5px;
}

/* 弹窗内部样式 */
.add-view-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 10px;
}

.content-txt1 {
  color: #333333;
  font-size: 16px;
  font-weight: 500;
}

.add-view-body {
  flex: 1;
  margin-bottom: 15px;
}

.add-view-footer {
  display: flex;
  justify-content: flex-end;
}

.close-icon {
  font-size: 22px;
  color: var(--el-color-primary, #409EFF);
  transition: all 0.3s;
}

.close-icon:hover {
  color: var(--el-color-primary-dark-2);
  transform: rotate(90deg);
}

.region-textarea {
  margin: 10px 0;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
}

.edit-actions {
  display: flex;
  margin: 10px 0;
}

.edit-action {
  display: flex;
  align-items: center;
  margin-right: 15px;
  color: var(--el-color-primary, #409EFF);
  cursor: pointer;
  transition: all 0.3s;
}

.edit-action:hover {
  color: var(--el-color-primary-dark-2);
}

/* 类型框样式 */
.typeBox {
  color: #333333;
}

.typeBox-item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.typeBox_title {
  width: 80px;
}

.elinp {
  width: 100%;
}

/* 滚动条样式 */
.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: #c0c4cc #f5f7fa;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.custom-scrollbar::-webkit-scrollbar {
  width: 8px;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 4px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background-color: #909399;
}

/* 内容区域 */
.shipContent {
  height: 100%;
  width: 100%;
  overflow-y: auto;
  padding: 10px;
  background-color: #ffffff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

/* Element UI 重写 */
:deep(.el-collapse) {
  border: none;
  background-color: transparent;
}

:deep(.el-collapse-item__header) {
  background-color: transparent;
  border: none;
  padding: 0;
  height: auto;
  margin-bottom: 5px;
}

:deep(.el-collapse-item__wrap) {
  background-color: transparent;
  border: none;
}

:deep(.el-collapse-item__content) {
  padding: 5px 0 0 15px;
}

:deep(.el-collapse-item__arrow) {
  display: none !important;
}

.active {
  transform: rotate(90deg);
}

:deep(.el-input__inner) {
  background-color: #ffffff;
  border-color: #dcdfe6;
  color: #333333;
}

:deep(.el-textarea__inner) {
  background-color: #ffffff;
  border-color: #dcdfe6;
  color: #333333;
}

:deep(.el-button) {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  color: #606266;
}

:deep(.el-button--primary) {
  background-color: var(--el-color-primary, #409EFF);
  border-color: var(--el-color-primary, #409EFF);
  color: #ffffff;
}

.addBox_list_inp {
  margin-bottom: 15px;
}
</style>
<style scoped src="@/assets/datePark.css"></style>